package com.zealousbd.adserver.webapp.filter;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.jstl.core.Config;

import com.zealousbd.adserver.Constants;

public class LocaleFilter implements Filter {

	FilterConfig filterConfig = null;
	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String locale = request.getParameter("locale");
        Locale preferredLocale = null;

        if (locale != null) {
            preferredLocale = new Locale(locale);
        }
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession(false);

        if (session != null) {
            if (preferredLocale == null) {
                preferredLocale = (Locale) session.getAttribute(Constants.PREFERRED_LOCALE_KEY);
            } else {
                session.setAttribute(Constants.PREFERRED_LOCALE_KEY, preferredLocale);
                Config.set(session, Config.FMT_LOCALE, preferredLocale);
            }

            if (preferredLocale != null && !(request instanceof LocaleRequestWrapper)) {
            	httpRequest = new LocaleRequestWrapper(httpRequest, preferredLocale);
            }
        }

        chain.doFilter(httpRequest, response);
        
        // Reset thread-bound LocaleContext.


	}

	public void init(FilterConfig config) throws ServletException {
		this.filterConfig = config;

	}

}
